#include "head.h"
//用户下载，服务端向客户端发文件
int send_file(const char *full_path, int net_fd){
    response_t response;
    bzero(&response, sizeof(response));
    int fd = open(full_path, O_RDWR);
    //检查文件是否存在
    if(fd == -1){
        response.status = 1;
        sprintf(response.args, "error: file dose not exists\n");
        send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);
        return -1;
    }
    //向客户端发送返回信息
    send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);

    //接收客户端发来的偏移量
    off_t offset;
    recv(net_fd, &offset, sizeof(off_t), MSG_WAITALL);

    //获取文件大小
    struct stat stat_file;
    fstat(fd, &stat_file);
    off_t file_size = stat_file.st_size;

    //发送文件大小
    send(net_fd, &file_size, sizeof(off_t), MSG_NOSIGNAL);
    //发送文件
    sendfile(net_fd, fd, &offset, file_size - offset);

    close(fd);
    return 0;
}

//用户上传，服务端接收客户端的文件
int recv_file(const char *full_path, int net_fd){

    response_t response;
    bzero(&response, sizeof(response));
    //向客户端发送返回信息
    send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);

    //接收客户端要上传的文件大小
    off_t file_size;
    recv(net_fd, &file_size, sizeof(off_t), MSG_WAITALL);

    int fd = open(full_path, O_RDWR | O_CREAT, 0666);

    //获取偏移量
    struct stat stat_file;
    fstat(fd, &stat_file);
    off_t offset = stat_file.st_size;

    //发送起始偏移量
    send(net_fd, &offset, sizeof(off_t), MSG_NOSIGNAL);

    ftruncate(fd, file_size);

    char *p =(char *)mmap(NULL, file_size, PROT_READ | PROT_WRITE,
                          MAP_SHARED, fd, 0);
    char *curr = p + offset;

    //接收文件
    int recv_count = recv(net_fd, curr, file_size - offset, MSG_WAITALL);

    offset += recv_count;

    munmap(p, file_size);
    ftruncate(fd, offset);

    close(fd);
    return 0;
}
